<template>
  <div class="app-container">
    <div class="chart_container">
      <div class="chart_box mb20">
        <div class="circle_container">
          <div>
            <div class="circle_title">
              {{ t("dashboard.assetsCount") }}
              <span :style="{ color: 'var(--el-color-primary)' }"
                >({{ assetsDataTotal || 0 }})</span
              >
            </div>
          </div>

          <div v-if="statusDataOfProgress.length == 0" class="circle_skeleton_box">
            <el-skeleton
              class="circle_skeleton_item"
              v-for="item in 5"
              animated
              style="--el-skeleton-circle-size: 120px"
            >
              <template #template>
                <el-skeleton-item variant="circle" />
              </template>
            </el-skeleton>
          </div>
          <div v-else class="circle_box">
            <template v-for="(item, index) in statusDataOfProgress" :key="index">
              <div class="circle_item">
                <div>
                  <el-tooltip placement="right" effect="light" :open-delay="500">
                    <template #content>
                      <div v-html="getAssetHtml(item)"></div>
                    </template>
                    <el-progress
                      striped
                      striped-flow
                      :duration="10"
                      :width="100"
                      :percentage="getAssetsPersent(item)"
                      type="circle"
                      :color="
                        index == 0
                          ? '#67C23A'
                          : index == 3
                          ? '#E6A23C'
                          : index == 2
                          ? '#F56C6C'
                          : index == 1
                          ? '#409EFF'
                          : '#000000'
                      "
                    >
                    </el-progress>
                  </el-tooltip>
                </div>
                <div>{{ item.assetsTypeName }}</div>
              </div>
            </template>
          </div>
        </div>
      </div>

      <div class="chart_box mb20">
        <div class="proval_container">
          <approval></approval>
        </div>
      </div>
      <div v-for="(chart, index) in charts" :key="index" class="chart_box mb20">
        <div
          v-if="deptDataOfPie.length == 0 || incrementDataOfBar.length == 0"
          class="skeleton_box"
        >
          <div class="title">
            {{ chart.option.title.text }}
          </div>
          <el-skeleton style="margin: 0 20px; width: 90%" :rows="5" animated />
        </div>
        <v-chart v-else class="chart" :option="chart.option" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { GetAssetsList } from "@/api/assetsManage/assetsList";
import approval from "@/components/bigScreen/approval.vue";
import { getBigScreenData } from "@/api/bigScreen";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { PieChart, BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  DatasetComponent,
  GridComponent,
} from "echarts/components";
import VChart, { THEME_KEY } from "vue-echarts";

//按需引入 echarts 图表
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  BarChart,
  DatasetComponent,
  GridComponent,
]);
provide(THEME_KEY, "default");
const assetsDataTotal = ref(null); //总资产数,用来计算百分比
const statusDataOfProgress = ref([]); //状态的资产圆形进度条
const deptDataOfPie = ref([]); //组织的资产饼图
const incrementDataOfBar = ref([]); //资产增量的柱状图

const getAssetHtml = (item) => {
  return `${item.assetsTypeName}<br/>${t("dashboard.typeCount")} : ${item.assetsQty} ${t(
    "dashboard.typeUnit"
  )}`;
};

//查询大屏数据
const queryBigScreenData = () => {
  getBigScreenData("").then((res) => {
    const { assetsList, OwnershipOrgData, AssetIncrementData } = res.output;
    // console.log(assetsList, OwnershipOrgData, AssetIncrementData)
    statusDataOfProgress.value = assetsList;
    deptDataOfPie.value = OwnershipOrgData;
    incrementDataOfBar.value = AssetIncrementData;
  });
};

// 计算属性用于生成图表的配置
const pieChartOption = computed(() => ({
  title: {
    text: `${t("dashboard.orgStatistics")}`,
    left: "center",
  },
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c}个 ({d}%)",
  },
  legend: {
    orient: "vertical",
    // left: 'right',
    right: "20",
    data: deptDataOfPie.value.map((item) => ({
      name: item.orgName,
    })),
  },
  series: [
    {
      name: `${t("dashboard.assetCount")}`,
      type: "pie",
      radius: "50%",
      center: ["50%", "60%"],
      data: deptDataOfPie.value.map((item) => ({
        name: item.orgName,
        value: item.qty,
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    },
  ],
}));

const barChartOption = computed(() => ({
  title: {
    text: `${t("dashboard.assetIncrement")}`,
    left: "center",
  },
  tooltip: {
    trigger: "axis", // 使 tooltip 在轴上触发，以显示所有系列的数据
    axisPointer: {
      type: "shadow", // 使用阴影指示器
    },
    formatter: (params) => {
      // params 是一个数组，包含了所有系列的数据
      const month = params[0].name; // X 轴的标签
      const lastYearQty =
        params.find((p) => p.seriesName === `${t("dashboard.lastYearQuantity")}`)?.data ||
        0;
      const thisYearQty =
        params.find((p) => p.seriesName === `${t("dashboard.thisYearQuantity")}`)?.data ||
        0;

      return `${month}<br/>${t("dashboard.lastYearQuantity")}: ${lastYearQty} ${t(
        "dashboard.typeUnit"
      )} <br/>${t("dashboard.thisYearQuantity")}: ${thisYearQty} ${t(
        "dashboard.typeUnit"
      )}`;
    },
  },
  legend: {
    // 图例配置
    data: [`${t("dashboard.lastYearQuantity")}`, `${t("dashboard.thisYearQuantity")}`], // 显示的图例项
    bottom: 10, // 图例放置在底部
    textStyle: {
      color: "#333", // 图例文本颜色
      fontSize: 14, // 图例文本大小
    },
  },
  xAxis: {
    type: "category",
    data: incrementDataOfBar.value.map((item) => item.monthName),
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      name: `${t("dashboard.lastYearQuantity")}`,
      type: "bar",
      data: incrementDataOfBar.value.map((item) => item.LastYearQty),
      itemStyle: {
        color: "#FFAB00", // 设置颜色
      },
      barGap: "20%", // 设置柱间距
      barCategoryGap: "40%", // 设置类目间距
    },
    {
      name: `${t("dashboard.thisYearQuantity")}`,
      type: "bar",
      data: incrementDataOfBar.value.map((item) => item.ThisYearQty),
      itemStyle: {
        color: "#5470C6", // 设置颜色
      },
    },
  ],
}));

//// 使用 computed 来确保 charts 是响应式的
const charts = computed(() => [
  { option: barChartOption.value, key: "increment" },
  { option: pieChartOption.value, key: "dept" },
]);

const getAssetsPersent = (item) => {
  // 检查 assetsDataTotal.value 是否为有效数字且不为零
  if (!assetsDataTotal.value || assetsDataTotal.value === 0) {
    return 0; // 如果无效，返回 0
  }

  // 计算百分比
  const result = (item.assetsQty / assetsDataTotal.value) * 100;

  // 检查 result 是否为有效数字
  return isFinite(result) ? Math.ceil(result) : 0;
};

//获取资产总数
const queryList = () => {
  const params = {
    pagination: 0,
    pageRow: 9999,
    isInit: true,
    enableFlag: -1,
    IsCheck: -1,
  };
  GetAssetsList(params)
    .then((res) => {
      assetsDataTotal.value = res.output.count;
    })
    .catch((err) => {});
};

onMounted(() => {
  queryBigScreenData();
  queryList();
});
</script>

<style scoped lang="scss">
@media (max-width: 430px) {
  .circle_container {
    .circle_box,
    .circle_skeleton_box {
      position: absolute;
      top: 60px;
      .circle_item {
        .el-progress {
          width: 80px !important;
          height: 80px !important;
          :deep(.el-progress-circle) {
            width: 80px !important;
            height: 80px !important;
          }
        }
      }

      .circle_skeleton_item {
        --el-skeleton-circle-size: 80px !important;
      }
    }
  }
}

@media (max-width: 960px) {
  .chart_box {
    flex: 0 0 100% !important;
    margin-right: 0 !important;
    &:nth-child(2n) {
      margin-left: 0 !important;
    }
  }
}
@media (min-width: 961px) and (max-width: 1020px) {
  .chart_container {
    .chart_box {
      .circle_container {
        .circle_skeleton_box {
          position: absolute !important;
          top: 60px !important;
          // height: 20px !important;
        }
      }
    }
  }
}

.chart_container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
  overflow-y: auto;

  .chart_box {
    background: #fff;
    height: calc(50% - 20px);
    border-radius: 6px;
    position: relative;
    margin-bottom: 20px;
    margin-right: 20px; // 默认的右边距
    flex: 0 0 calc(50% - 20px); // 两列布局时的宽度

    &:nth-child(2n) {
      margin-right: 0; // 偶数项不需要右边距
      margin-left: 20px;
    }

    .circle_container {
      display: flex;
      flex-direction: column;
      justify-content: center;

      .circle_title {
        text-align: center;
        height: 30px;
        line-height: 30px;
        font-weight: bolder;
        font-size: 18px;
        margin: 20px 0;
      }

      .circle_box,
      .circle_skeleton_box {
        // position: absolute;
        // top: 60px;
        height: calc(100% - 60px);
        display: flex;
        flex-wrap: wrap;
        align-items: flex-start;
        overflow-y: auto;

        .circle_item,
        .circle_skeleton_item {
          flex: 0 0 calc((100% - 60px) / 3);
          height: 120px;
          display: flex;
          flex-direction: column;
          // justify-content: center;
          align-items: center;
          // width: calc(29% - 20px);
          margin-right: 20px;
          margin-bottom: 20px;
        }
      }
    }
    .skeleton_box {
      display: flex;
      flex-direction: column;
      .title {
        text-align: center;
        height: 30px;
        line-height: 30px;
        font-weight: bolder;
        font-size: 18px;
        margin: 20px 0;
      }
    }

    .chart {
      position: absolute;
      width: 100%;
      height: 90%;
      top: 10%;
    }

    .proval_container {
      position: absolute;
      height: 100%;
      width: 100%;
      overflow-y: hidden;

      .table_container {
        position: absolute;
        margin: 0 10px;
        width: calc(100% - 20px);
        height: calc(100% - 30px);
      }
    }
  }

  .chart_container {
    justify-content: space-between; // 确保元素在一行中的左右对齐
  }

  .chart_box:hover {
    box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
  }
}
</style>
